<template>
  <div class="container" v-swipe="handleSwipe">
    <!-- 播放器 -->
    <div ref="J_prismPlayer" id="J_prismPlayer"></div>

    <Transition name="slide-fade">
      <!-- 直播间顶部信息 -->
      <liveTop v-show="liveUI" :liveRoomId="liveRoomId" />
    </Transition>

    <Transition name="slide-fade">
      <!-- 评论和底部输入框 -->
      <liveBottom v-show="liveUI" @hideUI="hideUI" @handleLivePauses="handleLivePauses" @getLiveStream="getLiveStream"
        @handleLiveEnd="handleLiveEnd" />
    </Transition>

    <Transition name="slide-fade">
      <!-- 优惠券 -->
      <div class="Coupons" v-show="liveUI">
        <!-- <van-icon name="cross" class="closeCoupons" @click="handleCloseCoupons"/> -->
        <div @click="handleCoupons">
          <!-- <img src="/src/assets/icons/Coupons.png" alt=""> -->
        </div>
      </div>
    </Transition>

    <van-action-sheet v-model:show="showCoupons" title="优惠券">
      <div class="content">领取优惠券</div>
    </van-action-sheet>
  </div>
</template>

<script setup>
import Aliplayer from 'aliyun-aliplayer';
import 'aliyun-aliplayer/build/skins/default/aliplayer-min.css';
import liveTop from './liveTop.vue'
import liveBottom from './liveBottom.vue';
const liveRoomId = ref('') // 直播间ID;
import { useRoute } from 'vue-router';
const route = useRoute()
const liveId = ref(route.query.liveId) // 直播ID

const liveInfo = ref('')    // 直播基本信息

//#region播放器实例
const player = ref(null);   // 播放器实例
const J_prismPlayer = ref() // 播放器容器
const liveCover = ref()     // 直播封面
const liveStates = ref('')  // 直播状态
const liveStatusMap = ['直播未开始', '直播未开始', '正在推流', '已结束', '已失效', '主播暂时离开~']
const livePageTips = ref('直播未开始')

// 创建播放器实例
// 本地测试只能通过localhost 访问, 127.0.0.1也不行, 远程访问必须打包部署在License证书绑定的域名上
// 创建播放器实例
function createPlayer(liveRtsPullUrl, liveCover) {
  player.value = new Aliplayer({
    id: 'J_prismPlayer',      // 播放器容器id
    width: "100%",            // 播放器宽度
    height: "100%",           // 播放器高度
    source: liveRtsPullUrl, // 拉流地址
    isLive: true,             // 播放内容是否为直播，直播时会禁止用户拖动进度条。默认值为false，播放直播流时需要设置为true。
    license: {
      domain: "qiuxuemao.cn", // 申请 License 时填写的域名
      key: "MPtobXpwKs2LwZ2iM75a73058584a4f0eb8b9548ed8897b51" // 申请成功后，在控制台可以看到 License Key
    },
    cover: liveCover,               // 封面地址  
    autoplay: false,                // 自动播放
    // definition:'FD,LD,SD,HD,OD,2K,4K', // 没看到在哪控制
    snapshotWatermark: '小兵良品',   // 截图水印
    diagnosisButtonVisible: 'true', // 检测按钮
    controlBarVisibility: 'never',  // 隐藏控制面板
    skinLayout: [
      { name: "bigPlayButton", align: "tlabs", x: 0, y: 240 },   // 大播放按钮。
      { name: "errorDisplay", align: "tlabs", x: 0, y: 0 },    // 错误提示，当视频播放出错时的提示信息。
      { name: "H5Loading", align: "tlabs", x: 160, y: 210 },    // 加载动画
    ]
  },)
  // 当RTS拉流成功时触发，通过订阅该事件，可以获取到RTS TraceId。 回调函数的参数中traceId为拉流的TraceId，source为当前RTS流的播放地址。
  player.value.on('rtsTraceId', function (event) {
    console.log('拉流成功', event.paramData);
  })
  // 当RTS降级时触发，参数reason为降级的原因，fallbackUrl为降级到的地址。
  player.value.on('rtsFallback', function (reason, fallbackUrl) {
    console.log('降级时触发', reason);
    fallbackUrl(liveInfo.value.liveRtmpPullUrl)
  })
  // 播放出错时
  player.value.on('onM3u8Retry', function () {
    console.log('主播暂时离开，请稍后......');
  });
  //  尝试数据恢复失败时
  player.value.on('liveStreamStop', function () {
    console.log('直播已结束');
  });
  // 
  player.value.on('error', function (e) {
    // 获取错误信息
    const ErrorMessage = document.querySelector('.prism-ErrorMessage')

    //   console.log('错误信息:', e.paramData.error_msg);

    // 隐藏内部所有div结构
    ErrorMessage.querySelectorAll('div').forEach(div => div.style.display = 'none')
    // 给最外层添加背景图片
    const errDiv = document.createElement('div');
    livePageTips.value = e.paramData.error_msg
    errDiv.innerHTML = createDom()
    // div添加到ErrorMessage结构里
    ErrorMessage.appendChild(errDiv);
    // 监听点击事件
    // document.querySelector('#liveState').addEventListener('click', liveStateClick);

  });
}

// function liveStateClick() {
//   console.log('直播状态被点击');
// }

// 获取直播流地址

import { getLiveStreamApi } from '@/api/live/index'
function getLiveStream() {
  getLiveStreamApi(liveId.value).then((res) => {
    console.log('直播流信息', res);
    if (res.code == 200) {
      liveInfo.value = res.data
      liveRoomId.value = liveInfo.value.liveRoomId
      liveCover.value = liveInfo.value.liveCover
      liveStates.value = liveInfo.value.liveStatus
      livePageTips.value = liveStatusMap[liveInfo.value.liveStatus]
      // liveStatus	直播状态(0.未开始 1.进行中 2.正在推流 3.已结束 4.已失效 5.暂停推流)

      if (liveInfo.value.liveStatus == 2) {
        // 先把遮罩层去掉
        const liveMask = document.querySelector('#liveMask')
        liveMask.style.display = 'none'
        // 创建播放器实例
        createPlayer(liveInfo.value.liveRtsPullUrl, liveInfo.value.liveCoverPreview)
      } else {
        const liveMask = document.querySelector('#liveMask')
        if (liveInfo.value.backgroundImagePreview) {
          liveMask.style.background = `url(${liveInfo.value.backgroundImagePreview})`
          liveMask.style.backgroundSize = 'cover'
          liveMask.style.backgroundPosition = 'center center'
        }
        // 显示提示文字
        const liveState = document.querySelector('#liveState')
        liveState.innerText = liveStatusMap[liveInfo.value.liveStatus]
      }
    }
  })
}

onMounted(() => {
  let maskDiv = document.createElement('div');
  maskDiv.innerHTML = createDom()
  J_prismPlayer.value.appendChild(maskDiv)
  getLiveStream()
})

//#endregion

//#region 卡片推送逻辑
// 直播暂停逻辑处理
function handleLivePauses() {
  // 销毁播放器
  player.value?.dispose()
  // 创建遮罩层
  let liveMask = document.querySelector('#liveMask')

  if (!liveMask) {
    let maskDiv = document.createElement('div');
    maskDiv.innerHTML = createDom()
    J_prismPlayer.value.appendChild(maskDiv)
    liveMask = document.querySelector('#liveMask')
  }
  let liveState = document.querySelector('#liveState')
  liveMask.style.background = liveInfo.value.liveCover
  // // 显示提示文字
  liveState.innerText = '主播暂时离开~'
}
// 直播结束
function handleLiveEnd() {
  // 销毁播放器
  player.value?.dispose()
  // 创建遮罩层
  let liveMask = document.querySelector('#liveMask')

  if (!liveMask) {
    let maskDiv = document.createElement('div');
    maskDiv.innerHTML = createDom()
    J_prismPlayer.value.appendChild(maskDiv)
    liveMask = document.querySelector('#liveMask')
  }
  let liveState = document.querySelector('#liveState')
  liveMask.style.background = liveInfo.value.liveCover
  // // 显示提示文字
  liveState.innerText = '直播已结束'
}
//#endregion

//#region 直播页面UI
const liveUI = ref(true)
function hideUI() {
  liveUI.value = false
}
function handleSwipe(detail) {
  if (detail.direction === 'left') {
    liveUI.value = true
  } else {
    liveUI.value = false
  }
}
//#endregion

//#region 创建DOM结构
// 添加div结构
function createDom() {
  return `
      <div id="liveMask" style="
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        backdrop-filter: blur(8px);
        ${liveInfo.value.backgroundImagePreview ? `background-image: url(${liveInfo.value.backgroundImagePreview});` : 'background: #122436;'}
        background-size: cover;
        background-position: center center;
      ">
        <div id="liveState" style="
          position: absolute;
          top: 30%;
          left: 50%;
          transform: translate(-50%, -50%);
          text-align: center;
          font-size: 18px;
          font-weight: 700;
          padding:10px 15px;
          border-radius: 100px;
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          border: 1px solid #ccc;
        "> 
            ${livePageTips.value}
        </div>
      </div>
    `
}
//#endregion

//#region 优惠券
const showCoupons = ref(false)
function handleCoupons() {
  console.log('优惠券');
  showCoupons.value = true
}
//#endregion

</script>

<style lang="scss" scoped>
.container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.Coupons {
  position: absolute;
  top: 30%;
  right: 5px;
  z-index: 99;

  .closeCoupons {
    position: absolute;
    top: 0;
    right: 0;
  }
}

.content {
  height: 300px;
  padding: 20px;
  font-size: 16px;
}

#J_prismPlayer {
  width: 100%;
  height: 100vh;
}

// 播放按钮
:deep(.prism-big-play-btn) {
  top: 50%;
  left: 50% !important;
  transform: translate(-50%, -50%);
}

.slide-fade-enter-active {
  transition: all 0.5s ease;
}

.slide-fade-leave-active {
  transition: all 0.5s ease;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(200px);
  opacity: 0;
}
</style>